﻿// -----------------------------------------------------------------------
// <copyright file="UnityDependnecyResolverTests.cs">
// Copyright (c) 2013 Andrey Veselov. All rights reserved.
// License:  Microsoft Public License (MS-PL)
// Contacts: http://andrey.moveax.com  andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace Moveax.DataAccess.Cqrs.Highway.Bootstrappers.Unity.UnitTests
{
	using System.Collections.Generic;
	using System.Linq;
	using System.Reflection;
	using Microsoft.VisualStudio.TestTools.UnitTesting;
	using Moq;
	using Moveax.DataAccess.Cqrs.Highway.Bootstrappers.Unity;
	using Moveax.DataAccess.Cqrs.Highway.UnitTests.Model.Commands;

	[TestClass]
	public class UnityDependnecyResolverTests
	{
		[TestMethod]
		public void UnityResolveSingle()
		{
			// Arrange
			ICqrsDependencyResolver resolver = this.BuildResolver();
			IEnumerable<CqrsParameterOverride> paramsCache = this.GetOverrideParameters();

			// Act
			var obj = resolver.Resolve<ICommandHandler<AlwaysSuccessAsyncCommand>>(paramsCache);

			// Assert 
			Assert.IsNotNull(obj);
		}


		[TestMethod]
		public void UnityResolveAll()
		{
			// Arrange
			ICqrsDependencyResolver resolver = this.BuildResolver();
			IEnumerable<CqrsParameterOverride> paramsCache = this.GetOverrideParameters();

			// Act
			var objs = resolver.ResolveAll<ICommandHandler<AlwaysSuccessAsyncCommand>>(paramsCache);

			Assert.IsNotNull(objs);
			Assert.IsTrue(objs.Any());
		}

		private ICqrsDependencyResolver BuildResolver()
		{
			var modelsAssembly = Assembly.Load("Moveax.DataAccess.Cqrs.Highway.UnitTests.Model");
			var dalAssembly = Assembly.Load("Moveax.DataAccess.Cqrs.Highway.UnitTests.DataAccess");
			var builder = new CqrsDependencyResolverBuilder();

			builder.CollectQueryInterfaces(modelsAssembly);
			builder.BindQueries(dalAssembly);

			builder.CollectCommands(modelsAssembly);
			builder.BindCommandHandlers(dalAssembly);

			return builder.Build();
		}

		private IEnumerable<CqrsParameterOverride> GetOverrideParameters()
		{
			var mockedRepository = new Mock<IRepository>();
			var mockedDataSource = new Mock<IDataSource>();

			var paramsCache = new CqrsParameterOverride[] {
					new CqrsParameterOverride("repository", typeof(IRepository), mockedRepository.Object),
					new CqrsParameterOverride("dataSource", typeof(IDataSource), mockedDataSource.Object)
				};

			return paramsCache;
		}
	}
}
